package cn.tedu.ymg.product.service.impl;

import cn.tedu.ymg.commons.ex.ServiceException;
import cn.tedu.ymg.commons.pojo.vo.PageData;
import cn.tedu.ymg.commons.util.PageInfoToPageDataConverter;
import cn.tedu.ymg.commons.web.ServiceCode;
import cn.tedu.ymg.product.mapper.HappyMapper;
import cn.tedu.ymg.product.mapper.MessageMapper;
import cn.tedu.ymg.product.mapper.OrderMapper;
import cn.tedu.ymg.product.mapper.UserMapper;
import cn.tedu.ymg.product.pojo.entity.Happy;
import cn.tedu.ymg.product.pojo.entity.Message;
import cn.tedu.ymg.product.pojo.entity.Order;
import cn.tedu.ymg.product.pojo.entity.User;
import cn.tedu.ymg.product.pojo.param.UserAddNewParam;
import cn.tedu.ymg.product.pojo.param.UserLoginParam;
import cn.tedu.ymg.product.pojo.param.UserUpdateInfoParam;
import cn.tedu.ymg.product.pojo.vo.UserListItemVO;
import cn.tedu.ymg.product.pojo.vo.UserLoginInfoVO;
import cn.tedu.ymg.product.pojo.vo.UserStandardVO;
import cn.tedu.ymg.product.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;


@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private HappyMapper happyMapper;

   /* @Autowired
    private PasswordEncoder passwordEncoder;*/
    @Override
    public void login(UserLoginParam loginParam, HttpSession session) {
        log.debug("开始处理【用户登录】，参数{}",loginParam);

       /* // 从Admin对象中取出原密码，执行加密，再将密文存入到Admin对象中
        String rawPassword = loginParam.getPassword();
        String encodedPassword = passwordEncoder.encode(rawPassword);
        loginParam.setPassword(encodedPassword);*/

        UserLoginInfoVO userVo=userMapper.passwordByUsername(loginParam.getUsername());
        if (userVo!=null){
            if (userVo.getPassword().equals(loginParam.getPassword())){
                /*session.setAttribute("user",userVo);*/
                return;//登陆成功
            }
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"用户名或密码错误");
        }
        throw new ServiceException(ServiceCode.ERR_CONFLICT,"用户名或密码错误");
    }




    @Override
    public void addNew(UserAddNewParam userAddNewParam) {
        log.debug("开始处理【添加用户的业务】，参数{}",userAddNewParam);
        //检查用户名称是否被占用，如果被占用，则抛出异常
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //name=参数中的相册名称
        queryWrapper.eq("username",userAddNewParam.getUsername());
        int countByName = userMapper.selectCount(queryWrapper);
        log.debug("根据用户名称统计匹配的用户数量，结果：{}", countByName);
        if (countByName>0){
            String message = "添加用户失败，用户名称被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        //将用户数据写入到数据库中
        User user = new User();
        BeanUtils.copyProperties(userAddNewParam, user);

        int rows = userMapper.insert(user);
        if (rows !=1){
            String message = "添加用户失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的用户数据写入到数据库，完成！");
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除用户】的业务，参数：{}", id);
        User user = userMapper.selectById(id);
        if (user ==null){
            String message = "删除相册失败，Id不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }

        QueryWrapper<Happy> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",id);
        int countById = happyMapper.selectCount(queryWrapper);
        log.debug("根据用户名称统计匹配的用户数量，结果：{}", countById);
        if (countById >0){
            String message = "删除用户失败，仍有数据关联到此用户";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        QueryWrapper<Message> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userId",id);
        int countById1 = messageMapper.selectCount(queryWrapper1);
        log.debug("根据用户名称统计匹配的用户数量，结果：{}", countById1);
        if (countById1 >0){
            String message = "删除用户失败，仍有数据关联到此用户";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        QueryWrapper<Order> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("userId",id);
        int countById2 = orderMapper.selectCount(queryWrapper2);
        log.debug("根据用户名称统计匹配的用户数量，结果：{}", countById2);
        if (countById2 >0){
            String message = "删除用户失败，仍有数据关联到此用户";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        int rows = userMapper.deleteById(id);
        if (rows!=1){
            String message = "删除用户失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("从数据库删除用户，完成！");
    }

    @Override
    public void updateInfoById(Long id, UserUpdateInfoParam userUpdateInfoParam) {
        log.debug("开始处理【修改用户详情】的业务，ID:{},新数据：{}", id, userUpdateInfoParam);

        //检查相册是否存在，如果不存在，则抛出异常
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = userMapper.selectCount(queryWrapper);
        log.debug("根据用户ID统计匹配的用户数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改用户详情失败，用户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        // 检查相册名称是否被其它相册占用，如果被占用，则抛出异常
        QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("username", userUpdateInfoParam.getUsername())
                .ne("id", id);
        int countByName = userMapper.selectCount(queryWrapper2);
        log.debug("根据用户名称统计匹配的用户数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "修改用户详情失败，用户名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //执行修改
        User user = new User();
        BeanUtils.copyProperties(userUpdateInfoParam, user);
        user.setId(id);
        int rows = userMapper.updateById(user);
        if (rows!=1){
            String message = "修改用户失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("从数据库修改用户，完成！");
    }

    @Override
    public UserStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询用户详情】的业务，参数：{}", id);
        //AlbumStandardVO queryResult = albumMapper.getStandardById(id);//将查询到的结果返回
        UserStandardVO queryResult = userMapper.getStandardById(id);
        if (queryResult==null){
            String message = "查询用户失败，用户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        return queryResult;
    }

    @Override
    public PageData<UserListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<UserListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<UserListItemVO> list = userMapper.list();
        PageInfo<UserListItemVO> pageInfo = new PageInfo<>(list);
        PageData<UserListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        return pageData;
    }
}
